const router = require('koa-router')()
const { register, login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../res-model/index')


router.prefix('/api/user')

router.post('/register', async (ctx, next) => {
  const { username, password } = ctx.request.body
  try {
    const newUser = await register(username, password)
    ctx.body = new SuccessModel(newUser)
  } catch (e) {
    console.error(e);
    ctx.body = new ErrorModel(-1, `注册失败-${e.message}`)
  }
})
router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body
  const res = await login(username, password)
  if (res) {
    //验证成功，设置sessionuserinfo
    ctx.session.userInfo = { username }
    //返回成功
    ctx.body = new SuccessModel()
  } else {
    //返回失败
    ctx.body = new ErrorModel(-2, '登录验证失败')
  }
})

module.exports = router
